let connection = require("../dbutil/dbutil");
let myModule = require("./my-module");

function evaluate(oid, uid, text) {
    let osqls = "select * from `order` where oid = '"+ oid +"'"
    connection.query(osqls, function (err, result) {
        if (err) {
            console.log(err);
        } else {
            let esql = "INSERT INTO `evaluate` (`uid`, `pid`, `text`) VALUES (?, ?, ?)";
            let esqlparams=[uid, result[0].pid, text]
            connection.query(esql, esqlparams, function (err) {
                if (err) {
                    console.log(err);
                }
            })
        }
    })
}

function getInfo(uid, token, callback) {
    let sql = "select username from user where uid = ? and token = ?";
    let sqlparams=[uid, token]
    connection.query(sql, sqlparams, function (err, result) {
        if (err) {
            console.log(err);
        } else {
            let ret = {
                code: 1002,
                data: []
            }
            if (result.length > 0 && myModule.verifyToken(token)) {
                let esql = "SELECT * FROM `evaluate_view` WHERE uid = '" + uid + "'"
                connection.query(esql, function (err, result) {
                    if (err) {
                        console.log(err);
                    } else {
                        ret.code = 1001
                        ret.data = result
                        callback(ret)
                    }
                })
            } else {
                callback(ret)
            }
        }
    })
}

function deleteEvaluate(uid, token, eid, callback) {
    let sql = "select username from user where uid = ? and token = ?";
    let sqlparams=[uid, token]
    connection.query(sql, sqlparams, function (err, result) {
        if (err) {
            console.log(err);
        } else {
            let ret = {
                code: 1002,
                msg: "删除失败"
            }
            if (result.length > 0 && myModule.verifyToken(token)) {
                let tsql = "DELETE FROM `evaluate` WHERE eid = '" + eid + "'";
                connection.query(tsql, function (err) {
                    if (err) {
                        console.log(err);
                    } else {
                        ret.code = 1001
                        ret.msg = "删除成功"
                        callback(ret)
                    }
                })
            } else {
                callback(ret)
            }
        }
    })
}

exports.evaluate = evaluate
exports.getInfo = getInfo
exports.deleteEvaluate = deleteEvaluate